/**
 * 智能分析基类
 * 提供数据查询、结果标准化和AI接口预留
 */

import { configurationManager } from '../ConfigurationManager';

export class BaseAnalyzer {
    constructor(caseId, targetSubject = null) {
        this.caseId = caseId;
        this.targetSubject = targetSubject; // 目标分析对象

        // Load config
        this.config = configurationManager.getConfig(this.constructor.name);
    }

    /**
     * 设置分析目标对象
     * @param {Object} subject 目标对象
     */
    setTarget(subject) {
        this.targetSubject = subject;
    }

    /**
     * 生成银行账号过滤的IN子句
     * @returns {string} SQL IN子句或空字符串
     */
    getBankAccountFilter() {
        if (!this.targetSubject || !this.targetSubject.accounts.bank.length) {
            return '';
        }
        const accounts = this.targetSubject.accounts.bank.map(acc => `'${acc}'`).join(',');
        return `AND card_number IN (${accounts})`;
    }

    /**
     * 生成手机号过滤的IN子句
     * @returns {string} SQL IN子句或空字符串
     */
    getPhoneFilter() {
        if (!this.targetSubject || !this.targetSubject.accounts.phone.length) {
            return '';
        }
        const phones = this.targetSubject.accounts.phone.map(p => `'${p}'`).join(',');
        return `AND user_number IN (${phones})`;
    }

    /**
     * 执行SQL查询
     * @param {string} sql SQL查询语句
     * @param {Array} params 参数数组
     * @returns {Promise<Object>} {success, data, message}
     */
    async runQuery(sql, params = []) {
        try {
            if (!window.electronAPI) {
                throw new Error('Electron API not available');
            }
            const result = await window.electronAPI.data.query({
                caseId: this.caseId,
                sql: sql,
                params: params
            });
            if (!result.success) {
                console.error('查询失败:', result.message);
                return { success: false, data: [], message: result.message };
            }
            return { success: true, data: result.data || [], message: '' };
        } catch (error) {
            console.error('查询异常:', error);
            return { success: false, data: [], message: error.message };
        }
    }

    /**
     * 格式化日期字符串
     * @param {string} dateStr 日期字符串
     * @returns {string} 格式化后的日期
     */
    formatDate(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr;

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hour = String(date.getHours()).padStart(2, '0');
        const minute = String(date.getMinutes()).padStart(2, '0');

        return `${year}-${month}-${day} ${hour}:${minute}`;
    }

    /**
     * 格式化金额
     * @param {number} amount 金额
     * @returns {string} 格式化后的金额
     */
    formatAmount(amount) {
        if (amount === null || amount === undefined) return '0.00';
        return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    /**
     * 创建标准化的分析结果对象
     * @param {string} type 分析类型
     * @param {string} title 标题
     * @param {Array} data 数据
     * @param {string} summary 摘要
     * @param {string} level 严重等级: info, warning, danger
     * @returns {Object} 标准化结果对象
     */
    createResult(type, title, data, summary, level = 'info') {
        return {
            type,
            title,
            count: data.length,
            data,
            summary,
            level,
            timestamp: new Date().toISOString()
        };
    }
}
